package cn.iocoder.yudao.module.mqtt.service.mqtt;

import cn.iocoder.yudao.framework.tenant.core.context.TenantContextHolder;
import cn.iocoder.yudao.module.mqtt.dal.dataobject.mqtt.MqttMessageDO;
import cn.iocoder.yudao.module.mqtt.dal.mysql.mqtt.MqttMessageMapper;
import cn.iocoder.yudao.module.mqtt.framework.util.TenantContextUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;

/**
 * MQTT消息服务
 *
 * @author 芋道源码
 */
@Slf4j
@Service
public class MqttMessageService {

    @Autowired
    private MqttMessageMapper mqttMessageMapper;

    /**
     * 保存消息到数据库
     */
    public void saveMessage(Long mqttConfigId, String topic, String payload, Integer qos, 
                           Boolean retained, String direction, String clientId, String messageId) {
        try {
            TenantContextUtil.executeWithTenantContext(() -> {
                MqttMessageDO message = MqttMessageDO.builder()
                        .mqttConfigId(mqttConfigId)
                        .topic(topic)
                        .payload(payload)
                        .qos(qos != null ? qos : 0)
                        .retained(retained != null ? retained : false)
                        .direction(direction)
                        .clientId(clientId)
                        .messageId(messageId)
                        .timestamp(LocalDateTime.now())
                        .build();
                if(topic.equals("ping/test")){
                    System.out.println( message);
                }else{
                    mqttMessageMapper.insert(message);
                }

            });
            
            log.debug("消息保存成功，配置ID: {}, 主题: {}, 方向: {}", mqttConfigId, topic, direction);
        } catch (Exception e) {
            log.error("消息保存失败，配置ID: {}, 主题: {}, 方向: {}", mqttConfigId, topic, direction, e);
        }
    }

    /**
     * 保存接收到的消息
     */
    public void saveReceivedMessage(Long mqttConfigId, String topic, String payload, 
                                   Integer qos, Boolean retained, String clientId, String messageId) {
        saveMessage(mqttConfigId, topic, payload, qos, retained, "IN", clientId, messageId);
    }

    /**
     * 保存发送的消息
     */
    public void saveSentMessage(Long mqttConfigId, String topic, String payload, 
                               Integer qos, Boolean retained, String clientId, String messageId) {
        saveMessage(mqttConfigId, topic, payload, qos, retained, "OUT", clientId, messageId);
    }
} 